using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;


public class ByteArray
{
    //默认长度 
    private const int DEFAULT_SIZE = 1024;
    //字节数组
    public byte[] bytes;

    //读的位置
    public int readIndex;

    //写的位置
    public int writeIndex;

    //初始大小
    private int initSize;

    //数组容量
    private int capacity;

    //读写之间的长度
    public int Length
    {
        get
        {
            return writeIndex - readIndex;
        }
    }

    //余量
    public int Remain
    {
        get
        {
            return capacity - writeIndex;
        }
    }

    /// <summary>
    /// 创建字节数组
    /// </summary>
    /// <param name="size">字节数组长度</param>
    public ByteArray(int size = DEFAULT_SIZE)
    {
        bytes = new Byte[size];
        initSize = size;
        capacity = size;
        readIndex = 0;
        writeIndex = 0;
    }

    /// <summary>
    /// 创建字节数组
    /// </summary>
    /// <param name="defaultBytes">默认的字节数组</param>
    public ByteArray(byte[] defaultBytes)
    {
        bytes = defaultBytes;
        initSize = defaultBytes.Length;
        capacity = defaultBytes.Length;
        readIndex = 0;
        writeIndex = defaultBytes.Length;
    }

    /// <summary>
    /// 移动数据
    /// </summary>
    public void MoveBytes()
    {
        if (Length > 0)
        {
            Array.Copy(bytes, readIndex, bytes, 0, Length);
            writeIndex = Length;
            readIndex = 0;
        }
    }

    /// <summary>
    /// 扩容
    /// </summary>
    public void ReSize(int size)
    {
        if (size < Length || size < initSize)
        {
            return;
        }

        capacity = size;
        byte[] newBytes = new byte[capacity];
        Array.Copy(bytes, readIndex, newBytes, 0, Length);
        bytes = newBytes;
        writeIndex = Length;
        readIndex = 0;
    }
}